package cn.it.shop.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

import javax.activation.MimetypesFileTypeMap;

/**
 * ClassName: HttpPostUploadUtil
 * @Description: 多媒体上传,模拟表单上传的工具类
 * @author fangyangsheng
 */
public class HttpPostUploadUtil {  

    public String urlStr; 
    
    /**
     * 初始化多媒体上传接口路径,加上参数access_token和长传类型为image
     */
    public HttpPostUploadUtil(){
        //urlStr = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token="+GlobalConstants.getInterfaceUrl("access_token")+"&type=image";  
        urlStr = GlobalConstants.getInterfaceUrl("mediaUrl") + GlobalConstants.getInterfaceUrl("access_token")+"&type=image";  
    }
    
    /**
     * 初始化多媒体上传接口路径,加上参数access_token和长传类型为image(带参数的)
     */
    public HttpPostUploadUtil(String type){
        urlStr = GlobalConstants.getInterfaceUrl("mediaUrl") + GlobalConstants.getInterfaceUrl("access_token")+"&type="+type;  
    }
    
    public HttpPostUploadUtil(String url,String type){
        urlStr = GlobalConstants.getInterfaceUrl(url) + GlobalConstants.getInterfaceUrl("access_token")+"&type="+type;  
    }

    /** 
     * 上传图片,返回包含media_id的json
     *  
     * @param urlStr 
     * @param textMap 
     * @param fileMap 
     * @return 返回文件上传后的路径  
     */  
    @SuppressWarnings("rawtypes")
    public String formUpload(Map<String, String> textMap,  
            Map<String, String> fileMap) {  
        String res = "";  
        HttpURLConnection conn = null;  
        String BOUNDARY = "---------------------------123821742118716"; //boundary 就是 request 头和上传文件内容的分隔符  
        try {  
            URL url = new URL(urlStr); 
            /**
             * 此处的urlConnection对象实际上是根据URL的   
             	请求协议(此处是http)生成的URLConnection类   
             	的子类HttpURLConnection,故此处最好将其转化   
             	为HttpURLConnection类型的对象,以便用到   
             	HttpURLConnection更多的API
             */
            conn = (HttpURLConnection) url.openConnection();  
            conn.setConnectTimeout(5000); //设置连接超时时间 
            conn.setReadTimeout(30000);  
            /**
             *  设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在   
             	http正文内，因此需要设为true, 默认情况下是false;
             */	  
            conn.setDoOutput(true);  
            // 设置是否从httpUrlConnection读入，默认情况下是true; 
            conn.setDoInput(true);  
            // Post 请求不能使用缓存 
            conn.setUseCaches(false);  
            conn.setRequestMethod("POST");  
            //设置请求头文报属性
            conn.setRequestProperty("Connection", "Keep-Alive");  
            //
            conn  
                    .setRequestProperty("User-Agent",  
                            "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");  
            conn.setRequestProperty("Content-Type",  
            		//有了boundary分隔符,各个参数之间才能隔开传到后台
                    "multipart/form-data; boundary=" + BOUNDARY);  
            
         /** 此处getOutputStream会隐含的进行connect(即：如同调用上面的connect()方法，   
        	所以在开发中不调用上述的connect()也可以,以上所有配置必须要在connect之前完成)。
          */	
            OutputStream out = new DataOutputStream(conn.getOutputStream());  
            // text  
            if (textMap != null) {  
                StringBuffer strBuf = new StringBuffer();  
                Iterator<?> iter = textMap.entrySet().iterator();  
                while (iter.hasNext()) {  
                    Map.Entry entry = (Map.Entry) iter.next();  
                    String inputName = (String) entry.getKey();  
                    String inputValue = (String) entry.getValue();  
                    if (inputValue == null) {  
                        continue;  
                    }  
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append(  
                            "\r\n");  
                    strBuf.append("Content-Disposition: form-data; name=\""  
                            + inputName + "\"\r\n\r\n");  
                    strBuf.append(inputValue);  
                }  
                out.write(strBuf.toString().getBytes());  
            }  

            // file  
            if (fileMap != null) {  
                Iterator<?> iter = fileMap.entrySet().iterator();  
                while (iter.hasNext()) {  
                    Map.Entry entry = (Map.Entry) iter.next();  
                    String inputName = (String) entry.getKey();  
                    String inputValue = (String) entry.getValue();  
                    if (inputValue == null) {  
                        continue;  
                    }  
                    File file = new File(inputValue);  
                    String filename = file.getName();  
                    String contentType = new MimetypesFileTypeMap()  
                            .getContentType(file);//设置文件类型
                    if (filename.endsWith(".jpg")) {  
                        contentType = "image/jpg";  
                    }  
                    if (contentType == null || contentType.equals("")) {  
                        contentType = "application/octet-stream"; //以流的形式 
                    }  

                    StringBuffer strBuf = new StringBuffer();  
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append(  
                            "\r\n");  
                    strBuf.append("Content-Disposition: form-data; name=\""  
                            + inputName + "\"; filename=\"" + filename  
                            + "\"\r\n");  
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");  

                    out.write(strBuf.toString().getBytes());  
                    DataInputStream in = null;
                    if(inputValue.indexOf("http") != -1){
	                    //文件流是无法打开网络上的文件的
	                    URL fileUrl = new URL(inputValue);
	                   
	                    InputStream urlsssss = fileUrl.openStream();
	                    if(urlsssss!= null){
	                    	System.out.println(urlsssss);
	                    }
	                    
	                    in = new DataInputStream(fileUrl.openStream());  
                    }else{
                        // 原本的写法
                    	in = new DataInputStream(  
                                 new FileInputStream(file));
                    }

                    int bytes = 0;  
                    byte[] bufferOut = new byte[1024];  
                    while ((bytes = in.read(bufferOut)) != -1) {  
                        out.write(bufferOut, 0, bytes);  
                    }  
                    in.close();  
                }  
            }  

            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();  
            out.write(endData);  
            out.flush();  
            out.close();  

            // 读取返回数据  
            StringBuffer strBuf = new StringBuffer();  
            BufferedReader reader = new BufferedReader(new InputStreamReader(  
                    conn.getInputStream()));  
            String line = null;  
            while ((line = reader.readLine()) != null) {  
                strBuf.append(line).append("\n"); //获取输入流内容 
            }  
            res = strBuf.toString();//返回接口返回结果
            reader.close();  
            reader = null;  
        } catch (Exception e) {  
            System.out.println("发送 POST 请求出错。" + urlStr);  
            e.printStackTrace();  
        } finally {  
            if (conn != null) {  
                conn.disconnect();  
                conn = null;  
            }  
        }  
        System.out.println("请求接口返回的json   "+res);
        return res;  
    }  

    
    
    
    

}